package cn.xaut.数组;

import java.util.Arrays;

public class demo167 {

    // 双指针（对撞指针）
    public int[] twoSum(int[] nums, int target) {

        int l = 0, r = nums.length - 1;
        while (r > l) {
            int sum = nums[l] + nums[r];
            if (sum == target)
                return new int[]{l + 1, r + 1};
            else if (sum > target)
                r --;
            else
                l ++;
        }
        return null;
    }
    
    // 二分查找
    public int[] twoSum2(int[] nums, int target) {

        int len = nums.length;
        for (int i = 0; i < len; i++) {
            int dest = target - nums[i];
            int l = i + 1, r = len - 1, mid = (l + r) / 2;
            while (r >= l) {
                if (nums[mid] == dest)
                    return new int[]{i + 1, mid + 1};
                else if (nums[mid] > dest) 
                    r = mid - 1;
                else     // nums[mid] < dest
                    l = mid + 1;
                mid = (l + r) / 2;
            }
        }
        
        return null;
    }

    public static void main(String[] args) {

        System.out.println(Arrays.toString(new demo167().twoSum2(new int[]{2, 7, 11, 15}, 9)));//[1, 2]
        System.out.println(Arrays.toString(new demo167().twoSum2(new int[]{2, 3, 4}, 6)));//[1, 2]
    }
    
}
